import {
  deleteTopic,
  selectCuesTopicManage,
  selectTopicManageTreeAssignOrganization,
  selectTopicManageTreeLinkageOrganization
} from '@/services/api/api-cues-topic';
import {
  CloseCircleOutlined,
  FileTextOutlined,
  LikeOutlined,
  StopOutlined
} from '@ant-design/icons';
// import { ProFormCascader } from '@ant-design/pro-components';
import { ModalForm, ProFormCascader } from '@ant-design/pro-components';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import { Avatar, Button, Card, Cascader, Descriptions, Divider, Space, Tag, Typography, message } from 'antd';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import ReceiptReport from '../components/ReceiptReport';
import TableSubmit from './TableTopicSubmit';
import TableTopicManageUpdate from './TableTopicManageUpdate';
interface TableTableTopicRenderDetailsProps {
  item: CuesTopicData.TopicPage;
  onRefurbish: () => void;
  title: string;
  triggerMode: 'card' | 'title';
  topicId: string
}

const TableTableTopicRenderDetails: React.FC<TableTableTopicRenderDetailsProps> = ({
  item,
  onRefurbish,
  title,
  triggerMode,
  topicId
}) => {
  const access = useAccess();

  const formRef = useRef<ProFormInstance>();

  const [loading, setLoading] = useState(false);

  const [drawerFormVisible, setDrawerFormVisible] = useState(false);


  /**
   * 指派单位数据
   */
  const [treeAssignOrganizationData, setTreeAssignOrganizationDataState] = useState();

  /**
   * 联动单位数据
   */
  const [treeLinkageOrganizationData, setTreeLinkageOrganizationDataState] = useState();

  /**
   * 选题计划详情
   */
  const [dataTopicDetails, setDataTopicDetailsState] = useState<CuesTopicData.TopicSelectManage>();

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          label: val.name,
          value: val.id,
          disabled: val.isFolder === 1 && val.isOrganization === 0 && val.children === undefined,
          children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
        });
      });
    }
    return treeData;
  }

  useEffect(() => {
    console.log(topicId);
    if (topicId === item.id) {

      if (topicId !== undefined) {
        setDrawerFormVisible(true)
      }
    }
  }, [])


  /**
   * 加载 保存 推送 单位
   */
  const loadSelectTopicManageTreeAssignOrganization = async () => {
    try {
      const response = await selectTopicManageTreeAssignOrganization({ id: topicId ? topicId : item.id });
      if (response.code === 0) {
        setTreeAssignOrganizationDataState(readyTreeData(response.data));
      }
    } catch (error) { }
  };

  /**
   * 加载 保存 联动 单位
   */
  const loadSelectTopicManageTreeLinkageOrganization = async () => {
    try {
      const response = await selectTopicManageTreeLinkageOrganization({
        id: item.id,
      });
      if (response.code === 0) {
        setTreeLinkageOrganizationDataState(readyTreeData(response.data));
      }
    } catch (error) { }
  };

  /**
   * 加载 选题计划详情
   * @param key
   */
  const loadCuesTopicDetails = async () => {
    setLoading(true);
    try {
      const response = await selectCuesTopicManage({ id: item.id });
      const { code, data } = response;
      if (code === 0) {
        setDataTopicDetailsState(data);
        console.log('=============', data.cascaderAssignOrganizations);

        formRef.current?.setFieldsValue({
          deadlineTime: [data.createdTime, data.deadlineTime],
          assignOrganizationIds: data.cascaderAssignOrganizations,
          linkageOrganizationIds: data.cascaderLinkageOrganizations,
        });

        setLoading(false);
      }
    } catch (error) { }
  };

  /**
   * 级联组件 搜索筛选
   * @param inputValue
   * @param path
   * @returns
   */
  const filter = (inputValue: string, path) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  const IconText = ({ icon, text }: { icon: any; text: string }) => (
    <span style={{ color: '#1677FF' }}>
      {React.createElement(icon, { style: { marginInlineEnd: 8 } })}
      {text}
    </span>
  );

  const TitleText = ({ title, text }: { title: string; text: any }) => (
    <div style={{ color: '#1677FF' }}>
      {title}：{text}
    </div>
  );

  const drawerFormView = () => {
    let cover = '';

    let gradeName = '';
    let gradeColor = '';

    if (item.grade === 1) {
      cover = 'https://wx4.sinaimg.cn/mw2000/0033ImPzly1hj076fx0z4j60p00p00w502.jpg';
      gradeName = '重大';
      gradeColor = '#f50';
    } else if (item.grade === 2) {
      cover = 'https://wx2.sinaimg.cn/mw2000/0033ImPzly1hj076fx3ilj60p00p0wi502.jpg';
      gradeName = '重要';
      gradeColor = '#ffd591';
    } else if (item.grade === 3) {
      cover = 'https://wx2.sinaimg.cn/mw2000/0033ImPzly1hj076fwx7zj60p00p0tc802.jpg';
      gradeName = '一般';
      gradeColor = '#2db7f5';
    }

    let linkageTypeName = '';

    if (item.linkageType === 1) {
      linkageTypeName = '协助媒体';
    } else if (item.linkageType === 2) {
      linkageTypeName = '联动部门';
    } else if (item.linkageType === 3) {
      linkageTypeName = '协助媒体、单位';
    } else {
      linkageTypeName = '暂无';
    }

    let recordActions: React.JSX.Element[] | React.ReactNode[] | undefined = [];

    if (item.recordState === 1) {
      recordActions = [
        <IconText icon={CloseCircleOutlined} text="废弃" key="list-vertical-star-o" />,
        <IconText icon={StopOutlined} text="撤销" key="list-vertical-star-o" />,
        <IconText icon={LikeOutlined} text="发布" key="list-vertical-like-o" />,
        <IconText icon={LikeOutlined} text="详情" key="list-vertical-like-o" />,
      ];
    } else if (item.recordState === 2) {
      recordActions = [
        <IconText icon={CloseCircleOutlined} text="废弃" key="list-vertical-star-o" />,
        <IconText icon={FileTextOutlined} text="详情" key="list-vertical-like-o" />,
      ];
    } else if (item.recordState === 3) {
      if (access.线索征集x配置x提供者) {
        recordActions = [
          <TitleText
            key={'title_text_count_submit_organization'}
            title="报送线索"
            text={item.countSubmit}
          />,
        ];
      } else {
        recordActions = [
          <TitleText
            key={'title_text_count_submit_organization'}
            title="报送单位"
            text={item.countSubmitOrganization}
          />,
          <TitleText key={'title_text_count_submit'} title="报送线索" text={item.countSubmit} />,
        ];
      }
    } else {
      recordActions = [<IconText icon={LikeOutlined} text="详情" key="list-vertical-like-o" />];
    }

    useEffect(() => {
      console.log(item);
    }, []);

    return (
      <DrawerForm
        key="add_topic_drawer_form"
        title={
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <div>
              <Tag color={gradeColor} style={{ fontSize: 10 }}>{gradeName}</Tag>
              <Tag color={item.run === 1 ? 'green' : item.run === 2 ? 'red' : 'orange'} style={{ fontSize: 10 }}>
                {item.run === 1 ? '进行中' : item.run === 2 ? '已结束' : '已暂停'}
              </Tag>
              {item.isLinkage === 1 && <Tag color="orange" style={{ fontSize: 10 }}>{linkageTypeName}</Tag>}
            </div>
            <div>
              <Space>
                {item.run === 1 && access.线索征集x配置x管理员 && (
                  <TableTopicManageUpdate
                    item={item}
                    onRefurbish={function (): void {
                      //加载权限树请求网络
                      loadSelectTopicManageTreeAssignOrganization();
                      loadSelectTopicManageTreeLinkageOrganization();
                      loadCuesTopicDetails();
                    }}
                  />
                )}
                {access.线索征集x配置x管理员 && <ModalForm
                  key={'modal_form_release_state_release'}
                  title={<>是否删除选题 : {item.name}</>}
                  trigger={<Button type="primary" danger >删除</Button>}
                  autoFocusFirstInput
                  modalProps={{
                    width: 400,
                    // bodyStyle: { textAlign: 'center' },
                    destroyOnClose: true,
                    onCancel: () => console.log('run'),
                  }}
                  submitTimeout={2000}
                  submitter={{
                    submitButtonProps: {
                      type: 'primary',
                      style: { background: '#FF5500' },
                    },
                  }}
                  onFinish={async (values) => {
                    const res = await deleteTopic({ id: item.id });
                    if (res.code === 0) {
                      message.success('删除成功');
                      setDrawerFormVisible(false)
                      onRefurbish()
                    }
                    return true;
                  }}
                >
                  {dataTopicDetails?.isSubmit === 1 ? '该选题已有报送线索，是否确定删除？' : ''}
                </ModalForm>}
              </Space>
            </div>
          </div>
        }
        drawerProps={{
          // maskClosable: false,
          destroyOnClose: true,
          width: '100%',
        }}
        visible={drawerFormVisible}
        loading={loading}
        formRef={formRef}
        trigger={
          triggerMode === 'card' ? (
            <div
              style={{
                paddingLeft: 10,
                paddingRight: 10,
                paddingBottom: 10,
              }}
            >
              <Card
                bordered={false}
                hoverable
                style={{
                  background: 'linear-gradient(#F5FBFF,#fff, #fff)',
                }}
                actions={recordActions}
              >
                <Card.Meta
                  avatar={
                    <Avatar
                      style={{
                        marginTop: '2px',
                      }}
                      size={'large'}
                      src={item.createdOrganizationAvatar}
                    />
                  }
                  title={
                    // <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <div>
                      <div
                        style={{
                          whiteSpace: 'nowrap',
                          overflow: 'hidden',
                          textOverflow: 'ellipsis',
                          minWidth: 65,
                        }}
                      >
                        {item.createdOrganizationName}
                      </div>
                      <div
                        style={{
                          float: 'left',
                        }}
                      >
                        <Tag color={gradeColor}>{gradeName}</Tag>
                        {item.isLinkage === 1 && <Tag color="orange">{linkageTypeName}</Tag>}
                        <Tag color={item.run === 1 ? 'green' : item.run === 2 ? 'red' : 'orange'}>
                          {item.run === 1 ? '进行中' : item.run === 2 ? '已结束' : '已暂停'}
                        </Tag>
                        {item.showView === 1 && item.isView === 0 ? (
                          <Tag color="red">未阅读</Tag>
                        ) : item.showSubmit === 1 && item.isSubmit === 0 ? (
                          <Tag color="red">未报送</Tag>
                        ) : (
                          <></>
                        )}
                      </div>
                    </div>
                  }
                  description={
                    <>
                      <Typography.Paragraph ellipsis={true}>
                        {
                          <span
                            style={{
                              color: '#888A8C',
                              fontSize: 15,
                            }}
                          >
                            {item.name}
                          </span>
                        }
                      </Typography.Paragraph>
                      <div
                        style={{
                          marginTop: 5,
                          marginRight: 18,
                          display: 'flex',
                          justifyContent: 'space-between',
                          width: '100%'
                        }}
                      >
                        <span
                          style={{
                            color:
                              item.run === 1 ? '#F47983' : item.run === 2 ? '#888A8C' : 'orange',
                          }}
                        >
                          截止：
                          {item.deadlineTime.slice(0, 11)}
                        </span>
                        <span
                          style={{
                            float: 'right',
                          }}
                        >
                          {moment(item.createdTime).fromNow()}
                        </span>
                      </div>
                    </>
                  }
                />
              </Card>
              <div
                style={{
                  borderRadius: 12,
                  background: '#FFF',
                }}
              ></div>
            </div>
          ) : (
            <a>{title}</a>
          )
        }
        initialValues={{}}
        onVisibleChange={(visible: boolean) => {
          if (visible) {
            //加载权限树请求网络
            loadSelectTopicManageTreeAssignOrganization();
            loadSelectTopicManageTreeLinkageOrganization();
            loadCuesTopicDetails();
          } else {
            onRefurbish();
          }
          setDrawerFormVisible(visible)
        }}
        onValuesChange={(values) => {
          console.log('========', values);

          if (values.assignOrganizationIds !== undefined) {
            formRef.current?.setFieldsValue({
              assignOrganizationIds: dataTopicDetails?.cascaderAssignOrganizations,
            });
          }
          if (values.linkageOrganizationIds !== undefined) {
            formRef.current?.setFieldsValue({
              linkageOrganizationIds: dataTopicDetails?.cascaderLinkageOrganizations,
            });
          }
          if (values.deadlineTime !== undefined) {
            formRef.current?.setFieldsValue({
              deadlineTime: [dataTopicDetails?.createdTime, dataTopicDetails?.deadlineTime],
            });
          }
        }}
        submitter={false}
        onFinish={async (values) => { }}
      >
        <Descriptions size="small">
          <Descriptions.Item label="单位">
            {dataTopicDetails?.createdOrganizationName}
            <div style={{ marginLeft: '20px' }}>
              {/* <Button size='small' type='primary' style={{ fontSize: 10 }}>发起采访</Button> */}
              <Button size='small' style={{ marginLeft: 1, fontSize: 10 }} type='primary'>创作写稿</Button>
            </div>
          </Descriptions.Item>
          <Descriptions.Item label="创建人">
            {dataTopicDetails?.createdAccountName}

          </Descriptions.Item>
          <Descriptions.Item label="联系方式">
            {dataTopicDetails?.createdAccountPhone}
          </Descriptions.Item>
        </Descriptions>
        <Descriptions size="small">
          <Descriptions.Item label="创建日期">
            <Typography.Text type="success">{dataTopicDetails?.createdTime}</Typography.Text>
          </Descriptions.Item>
          <Descriptions.Item label="截止日期">
            <Typography.Text type="danger">{dataTopicDetails?.deadlineTime}</Typography.Text>
          </Descriptions.Item>

          {access.线索征集x配置x管理员 && (
            <Descriptions.Item label="阅读情况">
              <ReceiptReport
                id={dataTopicDetails?.id}
                receipt={dataTopicDetails?.receipt}
                onRefurbish={() => {
                  onRefurbish();
                }}
              />
            </Descriptions.Item>
          )}
        </Descriptions>
        {dataTopicDetails && (
          <ProFormCascader
            width="xl"
            label={
              <span
                style={{
                  color: 'rgba(0, 0, 0, 0.45)',
                }}
              >
                指派征集单位：
              </span>
            }
            name="assignOrganizationIds"
            placeholder="选择单位"
            fieldProps={{
              options: treeAssignOrganizationData,
              // showSearch: { filter },
              // defaultValue: dataTopicDetails?.cascaderAssignOrganizations,
              multiple: true,
              removeIcon: false,
              allowClear: false,
              maxTagCount: 'responsive',
              showCheckedStrategy: Cascader.SHOW_CHILD,
            }}
          />)}
        {dataTopicDetails?.name ? (
          <div>
            <Typography.Title level={3} style={{ textAlign: 'center' }}>
              {dataTopicDetails?.name}

            </Typography.Title>

          </div>
        ) : (
          <></>
        )}

        <div
          style={{
            marginTop: 24,
          }}
        >
          <span
            style={{
              color: 'rgba(0, 0, 0, 0.45)',
            }}
          >
            选题内容：
          </span>
          <Typography.Paragraph>
            <blockquote>{dataTopicDetails?.content}</blockquote>
          </Typography.Paragraph>
        </div>

        {dataTopicDetails?.isLinkage === 1 && dataTopicDetails?.cascaderLinkageOrganizations && (
          <>
            <Divider />
            <ProFormCascader
              width="xl"
              label={
                <span
                  style={{
                    color: 'rgba(0, 0, 0, 0.45)',
                  }}
                >
                  {dataTopicDetails?.linkageType === 1
                    ? '协助媒体'
                    : dataTopicDetails?.linkageType === 2
                      ? '联动部门'
                      : dataTopicDetails?.linkageType === 3
                        ? '协助媒体、单位'
                        : '协助媒体、单位'}
                  ：
                </span>
              }
              name="linkageOrganizationIds"
              placeholder="选择单位"
              fieldProps={{
                options: treeLinkageOrganizationData,
                // showSearch: { filter },
                multiple: true,
                removeIcon: false,
                allowClear: false,
                maxTagCount: 'responsive',
                showCheckedStrategy: Cascader.SHOW_CHILD,
              }}
            />
            {dataTopicDetails?.linkageDescribes && (
              <div
                style={{
                  marginTop: 8,
                  color: 'rgba(0, 0, 0, 0.45)',
                }}
              >
                {dataTopicDetails?.linkageType === 1
                  ? '协助媒体描述'
                  : dataTopicDetails?.linkageType === 2
                    ? '联动部门描述'
                    : dataTopicDetails?.linkageType === 3
                      ? '协助媒体、单位描述'
                      : '协助媒体、单位描述'}
                ：
                <Typography.Paragraph>
                  <blockquote>{dataTopicDetails?.linkageDescribes}</blockquote>
                </Typography.Paragraph>
              </div>
            )}
          </>
        )}

        <TableSubmit
          mode={1} //开放页面
          item={item}
          onRefurbish={function (): void {
            onRefurbish();
          }}
        />
      </DrawerForm>
    );
  };

  return drawerFormView();
};
export default TableTableTopicRenderDetails;
